package cn.dida.core;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.ContentCachingRequestWrapper;

/**
 * 封装请求过滤器
 * @author weiwei
 */
public class WrapRequestFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new ContentCachingRequestWrapper((HttpServletRequest) request), response);
    }

   /* class MultiTimesBodyReadRequestWrapper extends HttpServletRequestWrapper {
        private final byte[] requestInputBytes;


        public MultiTimesBodyReadRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            try {
                InputStream inputStream = request.getInputStream();
                while ((rc = inputStream.read(buff)) > 0) {
                    outputStream.write(buff, 0, rc);
                }
            } finally {
                outputStream.close();
            }
            requestInputBytes = outputStream.toByteArray();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestInputBytes);
            ServletInputStream servletInputStream = new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {

                }

                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
            return servletInputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }
    }*/
}